package com.usian.admin.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.usian.admin.service.AdChannelService;
import com.usian.apis.admin.AdchannelControllerApi;
import com.usian.model.admin.dtos.ChannelDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@CrossOrigin
@RestController
@RequestMapping("/admin/api/v1/channel")
public class AdChannelController implements AdchannelControllerApi {

    @Autowired
    AdChannelService adChannelService;


    @PostMapping("/list")
    @Override
    public ResponseResult findByNameAndPage(@RequestBody ChannelDto channelDto) {
        return adChannelService.findNameByPage (channelDto);
    }

    @PostMapping("/save")
    @Override
    public ResponseResult save(@RequestBody AdChannel adChannel) {
        adChannelService.save (adChannel);
        return (ResponseResult.okResult (7777, "修改成功"));
    }

    @PostMapping("/update")
    @Override
    public ResponseResult update(@RequestBody AdChannel adChannel) {
        adChannelService.updateById (adChannel);
        return (ResponseResult.okResult (8888, "修改成功"));
    }

    @GetMapping("/del/{id}")
    @Override
    public ResponseResult del(@PathVariable Integer id) {
        adChannelService.removeById (id);
        return (ResponseResult.okResult (500, "删除成功"));
    }

    @GetMapping("/ExportExcel")
    public void ExportExcel() {
        // 设置文件导出的路径
        String realPath = "D://ce4/";
        File folder = new File (realPath);
        if (!folder.isDirectory ()) {
            folder.mkdirs ();
        }
        String fileName = realPath + "adChannel" + ".xlsx";
        List<AdChannel> list = adChannelService.list ();
        EasyExcel.write (fileName, AdChannel.class).sheet ("频道表").doWrite (list);
    }


    @PostMapping("/ImportExcel")
    public void ImportExcel(@RequestBody MultipartFile file) throws IOException {
        if (file.isEmpty ()) {
            return;
        }
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read (file.getInputStream (), AdChannel.class, new PageReadListener<AdChannel> (dataList -> {
            for (AdChannel adChannel : dataList) {
                //将导入的数据用mybatisPlus一个个添加进数据库
                adChannelService.save (adChannel);
            }
        })).sheet ().doRead ();
    }
}
